package org.example.project.bookstore.listener;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.bean.RocketMQOrder;
import org.example.project.bookstore.service.impl.ShoppingCartServiceImpl;
import org.example.project.bookstore.service.impl.UserServiceImpl;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @Auther:Liu
 * @Testname:OrderSuccessShoppingCartsLinstener
 * @Date:2025/8/27 10:09
 */
@Component
@Slf4j
@RocketMQMessageListener(consumerGroup = "order_success_3",topic = "order",selectorExpression = "transaction",messageModel = MessageModel.BROADCASTING)
public class OrderSuccessShoppingCartsLinstener implements RocketMQListener<String> {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void onMessage(String s) {
        log.info("开始执行成功操作,开始修改购物车信息");
        RocketMQOrder rocketMQOrder = JSON.parseObject(s, RocketMQOrder.class);
        log.info("rocketMQOrder数据为:{}",rocketMQOrder);
        //清空Redis个人购物车图书信息
        HashOperations<String, Object, Object> ops = stringRedisTemplate.opsForHash();
        log.info("ops:{}",ops);
        log.info("rocketMQOrder.getOrderItems():{}",rocketMQOrder.getOrderItems());
        rocketMQOrder.getOrderItems().forEach(item -> {
           ops.delete(ShoppingCartServiceImpl.SHOPPING_CART+rocketMQOrder.getUserId(),item.getBookId());
        });
        //清空图书显示信息
        Set<String> keys = stringRedisTemplate.keys("findCartByUserId*");
        log.info("所有的key:{}", keys);
        keys.forEach(item -> {
            log.info("删除:{}", item);
            stringRedisTemplate.delete(item);
        });

    }
}
